package com.conferenceroom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.conferenceroom.dto.RoomSelect;
import com.conferenceroom.entity.Orders;
import com.conferenceroom.entity.Record;
import com.conferenceroom.entity.Room;
import com.conferenceroom.mapper.OrdersMapper;
import com.conferenceroom.mapper.RoomMapper;
import com.conferenceroom.service.OrdersService;
import com.conferenceroom.service.RecordService;
import com.conferenceroom.service.RoomService;
import com.conferenceroom.vo.HourRoom;
import com.conferenceroom.vo.NowRoom;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements RoomService {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private RecordService recordService;

    @Autowired
    private RoomMapper roomMapper;

    private static final Logger logger = LoggerFactory.getLogger(RoomServiceImpl.class);
//    @Override
//    public List<Room> getAvailableRooms() {
//        QueryWrapper<Room> wrapper = new QueryWrapper<>();
//        wrapper.eq("status", 1); // status=1 表示空闲
//        return baseMapper.selectList(wrapper);
//    }

    @Override
    public List<Room> findAvailableRooms(RoomSelect roomSelect) {
        // 第一步：根据除时间外的条件筛选出会议室
        QueryWrapper<Room> roomQueryWrapper = new QueryWrapper<>();
        roomQueryWrapper.ge("capacity", roomSelect.getCapacity()); // 满足容量要求

        // 根据设备要求进行筛选
        if (roomSelect.getProjector() != null && roomSelect.getProjector() == 1) {
            roomQueryWrapper.eq("projector", 1);
        }
        if (roomSelect.getSound() != null && roomSelect.getSound() == 1) {
            roomQueryWrapper.eq("sound", 1);
        }
        if (roomSelect.getInternet() != null && roomSelect.getInternet() == 1) {
            roomQueryWrapper.eq("internet", 1);
        }

        List<Room> initialRooms = baseMapper.selectList(roomQueryWrapper);

        // 第二步：根据时间筛掉和“order表里状态为未支付和已支付的room”时间冲突的会议室
        List<Room> roomsAfterOrderCheck = initialRooms.stream()
                .filter(room -> isRoomAvailableDuringOrders(room.getRoomId(), roomSelect.getStartTime(), roomSelect.getEndTime()))
                .collect(Collectors.toList());

        // 第三步：根据时间筛掉和“维护表里状态为待处理、进行中的room”冲突的会议室
        List<Room> availableRooms = roomsAfterOrderCheck.stream()
                .filter(room -> isRoomAvailableDuringMaintenance(room.getRoomId(), roomSelect.getStartTime(), roomSelect.getEndTime()))
                .collect(Collectors.toList());

        // 获取会议室ID列表
        List<Integer> roomIds = availableRooms.stream()
                .map(Room::getRoomId)
                .collect(Collectors.toList());

        // 使用自定义SQL片段
        QueryWrapper<Room> queryWrapper = new QueryWrapper<>();

        if (!roomIds.isEmpty()) {
            queryWrapper.in("room_id", roomIds);
        }

        queryWrapper.last("ORDER BY (SELECT AVG(rating) FROM comment WHERE room_id = meeting_room.room_id) DESC");

        return this.list(queryWrapper);
    }

    private boolean isRoomAvailableDuringOrders(Integer roomId, Date startTime, Date endTime) {
        // 查询 order 表，找到在指定时间段内状态为未支付和已支付的订单
        QueryWrapper<Orders> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("room_id", roomId);
        orderQueryWrapper.in("payment_status", 0, 1, 4, 5);
        orderQueryWrapper.gt("end_time", startTime);
//        System.out.println(startTime);
        orderQueryWrapper.lt("start_time", endTime);


        List<Orders> conflictingOrders = ordersService.list(orderQueryWrapper);
//            System.out.println("recordList size: " + conflictingOrders.size());
        conflictingOrders.forEach(record -> System.out.println(record));

        // 如果没有冲突的订单，则该会议室可用
        return conflictingOrders.isEmpty();
    }

    private boolean isRoomAvailableDuringMaintenance(Integer roomId, Date startTime, Date endTime) {
        // 查询 maintenance_record 表，找到在指定时间段内状态为待处理或进行中的维护记录
        QueryWrapper<Record> maintenanceQueryWrapper = new QueryWrapper<>();
        maintenanceQueryWrapper.eq("room_id", roomId);
        maintenanceQueryWrapper.in("status", 1,2); // 状态为待处理（1）和进行中（2）

        List<Record> conflictingMaintenanceRecords = recordService.list(maintenanceQueryWrapper);

        // 如果没有冲突的维护记录，则该会议室可用
        return conflictingMaintenanceRecords.isEmpty();
    }

    // RoomServiceImpl.java
    @Override
    public IPage<Room> pageByCondition(IPage<Room> page, Room room) {
        QueryWrapper<Room> wrapper = new QueryWrapper<>();
        if (room.getRoomId() != null) {
            wrapper.eq("room_id", room.getRoomId());
        }
        if (StringUtils.hasLength(room.getRoomname())) {
            wrapper.like("roomname", room.getRoomname());
        }
        if (room.getRoomType() != null) {
            wrapper.eq("room_type", room.getRoomType());
        }
        if (room.getCapacity() != null) {
            wrapper.ge("capacity", room.getCapacity());
        }
        if (room.getStatus() != null) {
            wrapper.eq("status", room.getStatus());
        }
        if (room.getIsUse() != null) {
            wrapper.eq("is_use", room.getIsUse());
        }

        return baseMapper.selectPage(page, wrapper);
    }

    @Override
    public List<NowRoom> getCurrentRoomsStatus() {
        List<Room> rooms = roomMapper.selectList(new QueryWrapper<>());

        return rooms.stream().map(room -> {
            NowRoom nowRoom = new NowRoom();
            nowRoom.setRoomId(room.getRoomId());
            nowRoom.setRoomname(room.getRoomname());
            nowRoom.setRoomType(room.getRoomType());
            nowRoom.setCapacity(room.getCapacity());
            nowRoom.setProjector(room.getProjector());
            nowRoom.setSound(room.getSound());
            nowRoom.setInternet(room.getInternet());
            nowRoom.setPrice(room.getPrice());
            nowRoom.setArea(room.getArea());

            // 获取当前时间
            Date now = new Date();

            // 查询 maintenance_record 表中的状态
            QueryWrapper<Record> recordWrapper = new QueryWrapper<>();
            recordWrapper.eq("room_id", room.getRoomId())
                    .and(wrapper -> wrapper
                            .in("status", 1,2) // 待处理
                            .le("create_time", now)
                    );




//            Record currentRecord = recordService.getOne(recordWrapper);

            List<Record>recordList = recordService.list(recordWrapper);
//            System.out.println("recordList size: " + recordList.size());
//            recordList.forEach(record -> System.out.println(record));
            Record currentRecord = !recordList.isEmpty()? recordList.get(0): null;
            if (currentRecord != null) {
                nowRoom.setPaymentStatus(7); // 维修中
                return nowRoom;
            }





            // 查询 order 表中的状态
            QueryWrapper<Orders> orderWrapper = new QueryWrapper<>();
            orderWrapper.eq("room_id", room.getRoomId())
                    .and(wrapper -> wrapper
                            .eq("payment_status", 0)
                            .le("start_time", now)
                            .gt("end_time", now)
                            .or()
                            .eq("payment_status", 5)
                            .or()
                            .eq("payment_status", 1)
                            .le("start_time", now)
                            .gt("end_time", now)

                    );


            Orders currentOrder = ordersService.getOne(orderWrapper);

            if (currentOrder != null) {
                nowRoom.setPaymentStatus(currentOrder.getPaymentStatus());
                return nowRoom;
            }



            // 默认为空闲
            nowRoom.setPaymentStatus(6);
            return nowRoom;
        }).toList();
    }
    public List<HourRoom> getHourlyStatus(Integer roomId) {
        // 获取当前日期并设置为当天 00:00:00
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        // 构建当天的时间段（8:00 - 21:00）
        List<HourRoom> hourlyStatusList = new ArrayList<>();
        for (int hour = 8; hour <= 20; hour++) {
            HourRoom hourRoom = new HourRoom();
            hourRoom.setRoomId(roomId);
            hourRoom.setPaymentStatus(6); // 默认为空闲

            calendar.set(Calendar.HOUR_OF_DAY, hour);
            Date startTime = calendar.getTime();

            calendar.add(Calendar.HOUR_OF_DAY, 1);
            Date endTime = calendar.getTime();

            hourRoom.setStartTime(startTime);
            hourRoom.setEndTime(endTime);

            hourlyStatusList.add(hourRoom);
        }

        // 查询订单数据
        QueryWrapper<Orders> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("room_id", roomId)
                .in("payment_status", 0,1,4,5);
//                .le("start_time", calendar.getTime())
//                .ge("end_time", calendar.getTime());

        List<Orders> ordersList = ordersService.list(orderQueryWrapper);

        // 填充订单状态
        for (Orders order : ordersList) {
            for (HourRoom hourRoom : hourlyStatusList) {
                if (isTimeOverlap(hourRoom.getStartTime(), hourRoom.getEndTime(), order.getStartTime(), order.getEndTime())) {
                    hourRoom.setPaymentStatus(order.getPaymentStatus());
                    hourRoom.setOrderId(order.getOrderId());
                    hourRoom.setUserId(order.getUserId());
                }
            }
        }

        // 查询维修记录数据
        QueryWrapper<Record> recordQueryWrapper = new QueryWrapper<>();
        recordQueryWrapper.eq("room_id", roomId)
                .in("status", Arrays.asList(1, 2))
                .le("create_time", calendar.getTime())
                .ge("update_time", calendar.getTime());

        List<Record> recordsList = recordService.list(recordQueryWrapper);

        // 填充维修状态
        for (Record record : recordsList) {
            for (HourRoom hourRoom : hourlyStatusList) {
                if (isTimeOverlap(hourRoom.getStartTime(), hourRoom.getEndTime(), record.getCreateTime(), record.getUpdateTime())) {
                    if (hourRoom.getPaymentStatus() != 7) { // 如果已经被标记为维修中，则不再重复标记
                        hourRoom.setPaymentStatus(7);
                    }
                }
            }
        }

        return hourlyStatusList;
    }

    // 判断两个时间区间是否有重叠
    private boolean isTimeOverlap(Date start1, Date end1, Date start2, Date end2) {
        return start1.before(end2) && start2.before(end1);
    }

    @Override
    public List<Map<String, Object>> getRoomIdsByRoomName(String roomname) {
        return baseMapper.selectRoomIdsByRoomName(roomname);
    }

    @Override
    public List<Room> listRoomsSortedByRating(String order) {
        // 使用MyBatis-Plus的LambdaQueryWrapper简化条件构建
        LambdaQueryWrapper<Room> queryWrapper = new LambdaQueryWrapper<>();

        // 使用自定义SQL片段进行排序
        String sqlOrder = "DESC".equalsIgnoreCase(order) ?
                "(SELECT AVG(rating) FROM comment WHERE room_id = meeting_room.room_id) DESC" :
                "(SELECT AVG(rating) FROM comment WHERE room_id = meeting_room.room_id) ASC";

        queryWrapper.last("ORDER BY " + sqlOrder);

        return this.list(queryWrapper);
    }

}
